package com.vaccination.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vaccination.entity.CaseHistory;
import com.vaccination.entity.InoculationRecord;
import com.vaccination.entity.User;
import com.vaccination.service.CaseHistoryService;
import com.vaccination.service.UserService;
import com.vaccination.util.PageRequest;
import com.vaccination.util.PageResponse;
import com.vaccination.util.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

@RestController
public class CaseHistoryController {

    @Autowired
    private CaseHistoryService caseHistoryService;
    @Autowired
    private UserService userService;

    @PostMapping("/listCaseHistory")
    public PageResponse listCaseHistory(HttpServletRequest request, PageRequest page) {
        String loginUser = (String) request.getSession().getAttribute("loginUser");
        User user = JSONObject.parseObject(loginUser, User.class);
        if (user == null) {
            PageResponse pageResponse = new PageResponse();
            pageResponse.setMsg("请登陆");
            return pageResponse;
        }
        if (user.getRole() == 2) {
            user.setId(-1L);
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        IPage<CaseHistory> iPage = caseHistoryService.listCaseHistory(new Page<>(page.getPage(), page.getLimit()), user.getId());
        List<CaseHistory> records = iPage.getRecords();
        records.forEach(item -> {
            if (StringUtils.isBlank(item.getUsername()) && item.getUserId() != null) {
                User byId = userService.getById(item.getUserId());
                if (byId != null) {
                    item.setUsername(byId.getName());
                    item.setUserIdentity(byId.getIdentityNum());
                }
            }
            if (item.getHappenTime() != null) {
                item.setHappenTimeStr(dateFormat.format(item.getHappenTime()));
            }
        });
        return new PageResponse("0", "请求成功", iPage.getTotal(), records);
    }

    @GetMapping("/delCaseHistory")
    public Result delCaseHistory(Long id) {
        caseHistoryService.removeById(id);
        return Result.success("删除成功");
    }

    @PostMapping("/saveCaseHistory")
    public Result saveInoculation(CaseHistory record, HttpServletRequest request) throws ParseException {
        String loginUser = (String) request.getSession().getAttribute("loginUser");
        User user = JSONObject.parseObject(loginUser, User.class);
        if (user == null) {
            return Result.error("请登陆");
        }
        record.setUserId(user.getId());
        if (StringUtils.isNoneBlank(record.getUsername())){
            User byUsername = userService.getByUsername(record.getUsername());
            if(byUsername == null) {
                User newUser = new User();
                newUser.setUsername(record.getUsername());
                newUser.setName(record.getUsername());
                newUser.setPassword("123456");
                newUser.setRole(1);
                newUser.setStatus(1);
                userService.save(newUser);
                byUsername = newUser;
            }
            record.setUserId(byUsername.getId());
        }
        if (StringUtils.isNoneBlank(record.getHappenTimeStr())) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            record.setHappenTime(dateFormat.parse(record.getHappenTimeStr()));
        }
        caseHistoryService.save(record);
        return Result.success("添加成功");
    }

    @PostMapping("/updateCaseHistory")
    public Result updateInoculation(CaseHistory record) throws ParseException {
        if (record.getId() == null) {
            return Result.error("更新失败");
        }
        if (StringUtils.isNoneBlank(record.getHappenTimeStr())) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            record.setHappenTime(dateFormat.parse(record.getHappenTimeStr()));
        }else {
            record.setHappenTime(null);
        }
        caseHistoryService.updateById(record);
        return Result.success("更新成功");
    }
}
